package com.spring.boot.core.database;

import java.util.List;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.google.common.collect.Lists;
import com.spring.boot.core.utils.HashUtils;

public class DynamicDataSource extends AbstractRoutingDataSource {

	private static final String PUBLIC_DB = "public_db";
	private static final String USER_DB_PREFIX = "user_db";
	// user库数量
	private static int userDBIndex = 1;

	private static final ThreadLocal<String> dataSourceKey = new ThreadLocal<String>();

	@Override
	protected Object determineCurrentLookupKey() {
		return dataSourceKey.get();
	}

	public static void setUserdb(long userId) {
		int routerDBIndex = (int) (userId % userDBIndex);
		dataSourceKey.set(USER_DB_PREFIX + routerDBIndex);
	}

	public static void setUserdbByUid(String uid) {
		int hash = HashUtils.hash(uid);
		int routerDBIndex = (int) (hash % userDBIndex);
		dataSourceKey.set(USER_DB_PREFIX + routerDBIndex);
	}

	public static void setPublic() {
		dataSourceKey.set(PUBLIC_DB);
	}

	public static void clear() {
		dataSourceKey.set(null);
	}

	public static List<Integer> userdbIndex() {
		List<Integer> list = Lists.newArrayList();
		for (int i = 1; i <= userDBIndex; i++) {
			list.add(i);
		}
		return list;
	}

	public static void setUserDBIndex(int index) {
		userDBIndex = index;
	}
}
